import os
import requests

from rest_framework.views import APIView
from rest_framework.response import Response

from tools import tools
from tools.tools import auth_token, delete_dir, get_pic_name, get_favorite_id
from tools.const import BASE_DIR
from tools.spider import hua_ban, hua_ban_kw, get_header

from private_website.apps.app01 import models
from private_website.apps.app02 import ser


# Create your views here.


class Favorite(APIView):
    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        try:
            favorite_type = request.data.get('type')
            name = request.data.get('name')
            belong = request.data.get('belong')
            if favorite_type == 'L':
                c = models.Favorites.objects.count()
                f_id = get_favorite_id(user.username, belong, c)
                models.Favorites.objects.create(user=user, id=f_id, name=name)
            elif favorite_type == 'M':
                c = models.MFavorites.objects.count()
                f_id = get_favorite_id(user.username, belong, c)
                f_obj = models.Favorites.objects.filter(id=belong)
                if f_obj:
                    models.MFavorites.objects.create(favorite_id=belong, id=f_id, name=name)
                else:
                    raise Exception('该大收藏夹不存在')
            elif favorite_type == 'S':
                c = models.SFavorites.objects.count()
                f_id = get_favorite_id(user.username, belong, c)
                f_obj = models.MFavorites.objects.filter(id=belong)
                if f_obj:
                    obj = models.SFavorites.objects.create(favorite_id=belong, id=f_id, name=name)
                    path = BASE_DIR + '/static/' + user.username + '/cover/' + str(obj.id)
                    os.mkdir(path)
                else:
                    raise Exception('该中收藏夹不存在')
            else:
                return Response({'code': 200, 'msg': '传送参数异常'})
            obj = models.Favorites.objects.filter(user=user).all()
            obj_ser = ser.FavoriteSer(obj)
            dic['data'] = obj_ser.data
            return Response(dic)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
            method = request.query_params.get('method')
            favorite = request.query_params.get('favorite')
            favorite_obj = models.Favorites.objects.filter(user=user).all()
            favorite_ser = ser.FavoriteSer(favorite_obj, method=method, favorite=favorite)
            dic['data'] = favorite_ser.data
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class DelFavorite(APIView):
    @auth_token
    def post(self, request):
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        dic = {'code': 100, 'msg': 'ok'}
        try:
            method = request.data.get('type')
            favorite = request.data.get('favorite')
            if method == 'S':
                favorite_obj = models.SFavorites.objects.filter(favorite__favorite__user=user, id=favorite)
                if not favorite_obj:
                    raise Exception('该收藏夹不存在')
                path = BASE_DIR + '/static/' + user.username + '/cover/' + str(favorite_obj.first().id) + '/'
                delete_dir(path)
                img_obj = models.Image.objects.filter(favorite=favorite_obj.first()).all()
                for i in img_obj:
                    path = BASE_DIR + i.path
                    os.remove(path)
                del_obj = favorite_obj.first().favorite
                favorite_obj.delete()
                obj = models.SFavorites.objects.filter(favorite=del_obj).all()
                obj_ser = ser.SFavoriteSer(obj, many=True)
                dic['data'] = obj_ser.data
                return Response(dic)
            elif method == 'M':
                favorite_obj = models.MFavorites.objects.filter(favorite__user=user, id=favorite)
                if not favorite_obj:
                    raise Exception('该收藏夹不存在')
                s_obj = models.SFavorites.objects.filter(favorite=favorite_obj.first())
                if s_obj:
                    path = BASE_DIR + '/static/' + user.username + '/cover/' + s_obj.first().id
                    delete_dir(path)
                img = models.Image.objects.filter(favorite__favorite=favorite_obj.first()).all()
                if img:
                    for i in img:
                        path = BASE_DIR + i.path
                        os.remove(path)
            elif method == 'L':
                favorite_obj = models.Favorites.objects.filter(user=user, id=favorite)
                if not favorite_obj:
                    raise Exception('该收藏夹不存在')
                s_obj = models.SFavorites.objects.filter(favorite__favorite=favorite_obj.first())
                if s_obj:
                    path = BASE_DIR + '/static/' + user.username + '/cover/' + s_obj.first().id
                    delete_dir(path)
                img = models.Image.objects.filter(favorite__favorite__favorite=favorite_obj.first()).all()
                if img:
                    for i in img:
                        path = BASE_DIR + i.path
                        os.remove(path)
            else:
                return Response({'code': 200, 'msg': '请求格式不正确'})
            favorite_obj.delete()
            favorite_obj = models.Favorites.objects.all()
            favorite_ser = ser.FavoriteSer(favorite_obj)
            dic['data'] = favorite_ser.data
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class EditFavorite(APIView):
    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        favorite = request.data.get('favorite')
        try:
            favorite_obj = models.SFavorites.objects.filter(id=favorite)
            file = request.FILES.get('file')
            file_path = request.data.get('file')
            name = request.data.get('name')
            if len(name) == 0:
                return Response({'code': 200, 'msg': '收藏夹名不能为空'})
            if not file:
                if len(file_path) > 0:
                    if favorite_obj:
                        favorite_obj.update(name=name)
                        favorite_obj = models.SFavorites.objects.filter(favorite=favorite_obj.first().favorite)
                        favorite_ser = ser.SFavoriteSer(favorite_obj, many=True)
                        dic['data'] = favorite_ser.data
                        return Response(dic)
                    else:
                        return Response({'code': 200, 'msg': '收藏夹不存在'})
                else:
                    return Response({'code': 200, 'msg': '上传的图片异常'})
            if favorite_obj:
                cover = '/static/' + user.username + '/cover/' + favorite + '/'
                path = BASE_DIR + '/static/' + user.username + '/cover/' + favorite + '/'
                if len(os.listdir(path)) != 0:
                    del_cover = BASE_DIR + favorite_obj.first().cover
                    os.remove(del_cover)
                cover = cover + tools.get_pic_name(file.name)
                path = BASE_DIR + cover
                with open(path, 'wb') as f:
                    for content in file.chunks():
                        f.write(content)
                favorite_obj.update(cover=cover, name=name)
                favorite_obj = models.SFavorites.objects.filter(favorite=favorite_obj.first().favorite)
                favorite_ser = ser.SFavoriteSer(favorite_obj, many=True)
                dic['data'] = favorite_ser.data
            else:
                return Response({'code': 200, 'msg': '收藏夹不存在'})
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class Image(APIView):
    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        favorite = request.data.get('favorite')
        try:
            img = request.FILES.get('file')
            if not img:
                return Response({'code': 200, 'msg': '上传的图片异常'})
            favorite_obj = models.SFavorites.objects.filter(id=favorite).first()
            if not favorite_obj:
                return Response({'code': 200, 'msg': '收藏夹不存在'})
            path = '/static/' + user.username + '/img/' + tools.get_pic_name(img.name)
            p = BASE_DIR + path
            with open(p, 'wb') as f:
                for content in img.chunks():
                    f.write(content)
            img_url = models.Image.objects.create(favorite=favorite_obj, path=path, user=user)
            cover = BASE_DIR + '/static/' + user.username + '/cover/' + str(favorite)
            if len(os.listdir(cover)) == 0:
                models.SFavorites.objects.filter(id=favorite).update(cover=path)
                dic['data'] = {'img': img_url.path, 'cover': path}
            else:
                dic['data'] = {'img': img_url.path, 'cover': '/static/default.png'}
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()

        try:
            favorite = request.query_params.get('favorite')
            page = request.query_params.get('page')
            limit = request.query_params.get('limit')
            if len(limit) == 0 or len(page) == 0:
                page = 1
                limit = 20
            count = (int(page)-1) * int(limit)
            limit = int(limit)
            data = []
            dic['limit'], dic['page'] = limit, page
            if favorite == '-1':
                img_obj = models.Image.objects.filter(user=user)[count:count+limit]
                for i in img_obj:
                    data.append({'id': i.id, 'path': i.path})
            else:
                img_obj = models.Image.objects.filter(user=user, favorite=favorite)[count:count+limit]
                for i in img_obj:
                    data.append({'id': i.id, 'path': i.path})
            dic['data'] = data
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class DelImage(APIView):
    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        img_id = request.data.get('img_id')
        try:
            img = models.Image.objects.filter(user=user, id=img_id)
            if img:
                path = BASE_DIR + img.first().path
                if os.path.exists(path):
                    # print('删除')
                    favorite = img.first().favorite
                    os.remove(path)
                    img.delete()
                    all_img = models.Image.objects.filter(favorite_id=favorite).all()
                    all_img_ser = ser.ImageSer(all_img, many=True)
                    dic['data'] = all_img_ser.data
                else:
                    raise Exception('图片不存在')
            else:
                dic['code'] = 200
                dic['msg'] = '图片不存在'
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class NewImg(APIView):
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        data = {'kw': request.query_params.get('kw'),
                'page': request.query_params.get('page')
                }
        per_page = request.query_params.get('per_page')
        sort = request.query_params.get('sort')
        if len(per_page) != 0:
            data['per_page'] = per_page
        if len(sort) != 0:
            data['sort'] = sort
        try:
            dic['data'] = hua_ban(**data)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        favorite = request.data.get('favorite')
        url = request.data.get('url')
        img_type = request.data.get('type')
        try:
            header_ = get_header()
            resp = requests.get(url, headers=header_)
            file_name = url.split('/')[-1] + '.' + img_type.split('/')[-1]
            file_name = get_pic_name(file_name)
            path = BASE_DIR + '/static/' + user.username + '/img/' + file_name
            obj = models.SFavorites.objects.filter(id=favorite, favorite__favorite__user=user)
            if obj:
                with open(path, 'wb') as f:
                    f.write(resp.content)
                img_path = '/static/' + user.username + '/img/' + file_name
                img_obj = models.Image.objects.create(favorite=obj.first(), path=img_path, user=user)
                img_ser = ser.ImageSer(img_obj)
                favorite_ser = ser.SFavoriteInfoSer(obj.first())
                dic['data'] = favorite_ser.data
                dic['data']['img'] = img_ser.data
            else:
                dic['code'] = 200
                dic['msg'] = '该收藏夹不存在'
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class KwComplete(APIView):
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        q = request.query_params.get('kw')
        try:
            dic['data'] = hua_ban_kw(q)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)
